package network.tcp.nio.http;

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @program: bio
 * @description:
 * @author: zhanghz001
 * @create: 2020-10-27 19:39
 **/
public class HttpResponse {
    private String method;
    private String version;

    private String status;
    private String desc;
    private HashMap<String, String> headers = new HashMap<>();
    private HttpRequest httpRequest;

    public HttpResponse(HttpRequest request) {
        this.httpRequest = request;
    }

    public void sendStaticResource(SelectionKey selectionKey) {
        //得到可用的channel,进行通信
        try (SocketChannel client = (SocketChannel) selectionKey.channel();) {
            if (client != null) {
                StringBuilder sb = new StringBuilder();
                //请求行
                //HTTP/1.1 200 OK
                this.version = "HTTP/1.1";
                this.status = "200";
                this.desc = "OK";

                //3.给响应头赋值
//先获取浏览器请求的URI
                String requestURI = this.getHttpRequest().getRequestURI();
                if (requestURI != null) {
                    File file = new File(WEB_APP_PATH + requestURI);
//判断这个路径是否存在
                    if (!file.exists()) {
                        this.status = "404";
                        this.desc = "NOT FOUND";
                    }
                    if ("200".equals(this.status)) {
                        if ("/".equals(requestURI)) {
                            headers.put("Content‐Type", "text/html;charset=UTF‐8");
                        } else if ("/favicon.ico".equals(requestURI)) {
                            headers.put("Content‐Type", "image/x‐icon");
                        } else if ("/a.txt".equals(requestURI)) {
                            headers.put("Content‐Type", "text/html;charset=UTF‐8");
                        } else if ("/1.jpg".equals(requestURI)) {
                            headers.put("Content‐Type", "image/jpeg");
                        } else if ("/1.png".equals(requestURI)) {
                            headers.put("Content‐Type", "image/png");
                        }
                    } else {
                        //Content-Type: application/json; charset=GBK
                        headers.put("Content-Type", "text/html; charset=utf-8");
                    }
                }

                String httpResponseLine = this.version + " " + this.status + " " + this.desc;
                sb.append(httpResponseLine);
                sb.append("\r\n");

                //请求头
                Set<Map.Entry<String, String>> entries = headers.entrySet();
                for (Map.Entry<String, String> entry : entries) {
                    sb.append(entry.getKey()).append(": ").append(entry.getValue());
                    sb.append("\r\n");
                }

                //请求空行
                sb.append("\r\n");
                String s = sb.toString();
                System.out.println(s);
                ByteBuffer src = ByteBuffer.wrap(s.getBytes());
                client.write(src);

                //请求体
                //请求体不一定是字符串,单独操作
                byte[] bytes = getContent();
                ByteBuffer src2 = ByteBuffer.wrap(bytes);
                client.write(src2);
                // client.shutdownOutput();
                //
            }
            //设置非阻塞
            //
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放资源   加入到 try的小括号中

        }
    }

    public static final String WEB_APP_PATH = "mynio\\webapp";

    private byte[] getContent() {
        try {
//1.获取浏览器请求的URI
            String requestURI = this.getHttpRequest().getRequestURI();
            if (requestURI != null) {
                if ("200".equals(this.status)) {
//2.判断一下请求的URI,根据不同的URI来响应不同的东西
                    if ("/".equals(requestURI)) {
                        String s = "哎哟,妈呀,终于写完了.";
                        return s.getBytes();
                    } else/* if("/favicon.ico".equals(requestURI))*/ {
//获取一个ico文件
                        FileInputStream fis = new FileInputStream(WEB_APP_PATH +
                                requestURI);
//把ico文件变成一个字节数组返回
                        return IOUtils.toByteArray(fis);
                    }
                } else {
                    return "访问的资源不存在".getBytes();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    @Override
    public String toString() {
        return "HttpResponse{" +
                "method='" + method + '\'' +
                ", version='" + version + '\'' +
                ", status='" + status + '\'' +
                ", desc='" + desc + '\'' +
                ", headers=" + headers +
                ", httpRequest=" + httpRequest +
                '}';
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public HashMap<String, String> getHeaders() {
        return headers;
    }

    public void setHeaders(HashMap<String, String> headers) {
        this.headers = headers;
    }

    public HttpRequest getHttpRequest() {
        return httpRequest;
    }

    public void setHttpRequest(HttpRequest httpRequest) {
        this.httpRequest = httpRequest;
    }

}
